var app = angular.module('appService', []);

app.service("httpService", ["$http", function ($http) {
    var head = "http://localhost:8080";

    this.get = function (url, success, error) {
        $http.get(completeUrl(url)).then(function (response) {
            var data = response.data;
            if (data.result === "success") {
                if (typeof (success) === "function") {
                    success(data.message);
                }
                return data.message;
            }else{
                alert("请求失败：" + data.message);
            }
        }, errorRequest);
    };
    this.post = function (url, data, isJson, success, error) {
        var config = {};
        if (isJson !== true){
            config = {
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                transformRequest: function (data) {
                    return $.param(data);
                }
            };
        }
        $http.post(completeUrl(url), data, config).then(function (response) {
            var data = response.data;
            if (data.result === "success") {
                if (typeof (success) === "function") {
                    success(data.message);
                }
                return data.message;
            }else{
                alert("请求失败：" + data.message);
            }
        }, errorRequest);
    };

    this.upload=function(url, form, success, error){
        $http.post(url,form,{
            transformRequest: angular.identity,
            headers:{
                'Content-Type': undefined
            }
        }).then(function (response) {
            var data = response.data;
            if (data.result === "success") {
                if (typeof (success) === "function") {
                    success(data.message);
                }
                return data.message;
            }else{
                alert("请求失败：" + data.message);
            }
        }, errorRequest);
    };

    var completeUrl = function (url) {
        if (url.indexOf("/") === 0)
            return head + url;
        else
            return url;
    };
    var errorRequest = function () {
        alert("请求失败。");
    };
}]);
